package zack.project.domain.strategy.service.rule.tree.impl;

import zack.project.domain.strategy.adapter.repository.IStrategyRepository;
import zack.project.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import zack.project.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import zack.project.domain.strategy.service.rule.tree.ILogicTreeNode;
import zack.project.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import zack.project.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;


/**兜底奖品的决策树节点
 * @author A1793
 */
@Component("rule_luck_award")
@Slf4j
public class RuleLuckAwardLogicTreeNode implements ILogicTreeNode {
    @Resource
    private IStrategyRepository strategyRepository;

    /**
     *
     * @param userId
     * @param strategyId
     * @param awardId
     * @param ruleValue 兜底(积分奖品)规则节点的规则值:{101:1,100},奖品id,积分范围
     * @param endDateTime
     * @return
     */
    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId,
                                                     Long strategyId,
                                                     Integer awardId,
                                                     String ruleValue,
                                                     Date endDateTime) {

        log.info("规则过滤-兜底奖品 userId:{} strategyId:{} awardId:{} ruleValue:{}", userId, strategyId, awardId, ruleValue);
        String[] split = ruleValue.split(Constants.COLON);
        if (split.length == 0) {
            log.error("规则过滤-兜底奖品，兜底奖品未配置告警 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
            throw new RuntimeException("兜底奖品未配置 " + ruleValue);
        }
        // 兜底奖励配置
        Integer luckAwardId = Integer.valueOf(split[0]);
        String awardRuleValue = split.length > 1 ? split[1] : "";
        //扣减兜底奖品库存,通过延迟队列消费StrategyAwardStockKeyVO消息来更新数据库表{strategy_award}
        strategyRepository.
                awardStockConsumeSendQueue(StrategyAwardStockKeyVO.builder().awardId(awardId).strategyId(strategyId).build());
        // 返回兜底奖品
        log.info("规则过滤-兜底奖品 userId:{} strategyId:{} awardId:{} awardRuleValue:{}", userId, strategyId, luckAwardId, awardRuleValue);
        return DefaultTreeFactory.TreeActionEntity.builder()
                //兜底奖品是最终的决策节点,应直接接管
                .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                .strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
                        .awardId(luckAwardId)
                        .awardRuleValue(awardRuleValue)
                        .build())
                .build();
    }

}
